const { getAdmin } = require("../dao/admin");
const { getUser } = require("../dao/user");
const { verifyToken } = require("../util/token");

module.exports = {
	// 管理端token验证
	Token: () =>
		function (req, res, next) {
			const method = req.method.toLowerCase();
			// 判断请求路径是否需要token
			let reqPath = req.path;
			// 请求路径以/api/web开头
			if (/^\/api\/web/.test(reqPath)) {
				if (reqPath == "/api/web/admin/login" || reqPath == "/api/web/admin/register") {
					return next();
				} else {
					const { token } = req.headers;
					// 验证token
					verifyToken(token)
						.then(async (decode) => {
							// 判断这个token对应的管理员是否在数据库中					
							const admin = await getAdmin({ admin_id: decode.admin_id }).catch(
								(err) => {
									res.send(error(err));
								}
							);
							if (!admin) {
								throw new Error("登录凭证无效");
							} else {
								// 根据请求方法将解码信息挂载到req
								method == "get"
									? (req.query.admin_id = admin.admin_id)
									: (req.body.admin_id = admin.admin_id);
								next();
							}
						})
						.catch((err) => {
							res.send(fail("登录凭证无效或已过期"));
						});
				}
				return; 
			} 

			// 请求路径以/api/wx开头
			if (/^\/api\/wx/.test(reqPath)) {
				if (reqPath == "/api/wx/user/login" || reqPath == "/api/wx/user/register" || reqPath == "/api/wx/user/search" || reqPath == "/api/wx/user/getProjectInfo" || reqPath == "/api/wx/user/getPeopleDetail") {
					return next();
				} 
				else {
					const { token } = req.headers;
					// 验证token
					verifyToken(token)
						.then(async (decode) => {
							// 判断这个token对应的管理员是否在数据库中,这个方法还没写
							const user = await getUser({ user_id: decode.user_id }).catch(
								(err) => {
									res.send(error(err));
								}
							);
							if (!user) {
								throw new Error("登录凭证无效");
							} else {
								// 根据请求方法将解码信息挂载到req
								// console.log(user);
								
								method == "get"
									? (req.query.user_id = user.user_id)
									: (req.body.user_id = user.user_id);
								
								next();
							}
						})
						.catch((err) => {
							res.send(fail("登录凭证无效或已过期"));
						});
				}
				return;
			} 
			next();
		},
};
